import { getCsrfToken } from './utils';

interface RequestOptions extends RequestInit {
    reFormatError?: boolean;
    alertError?: boolean;
}

export async function request(url: string, options: RequestOptions = {}) {
    const { method = 'GET', reFormatError = true, alertError: handleError = true, ...restOptions } = options;
    
    // Add CSRF token for non-GET requests
    if (method !== 'GET') {
        const csrfToken = getCsrfToken();
        options.headers = {
            ...options.headers,
            'X-CSRFToken': csrfToken || '',
        };
    }

    const requestOptions: RequestInit = {
        method,
        mode: 'same-origin',
        ...restOptions,
        headers: {
            ...options.headers,
        },
    };

    try {
        const response = await fetch(url, requestOptions);
        
        if (!response.ok && reFormatError) {
            const errorData = await response.json().catch(() => null);
            const errorMessage = errorData?.error ||
                gettext("服务器响应错误") + `${response.status}): ${response.statusText}`;
            throw new Error(errorMessage);
        }
        
        return response;
    } catch (error) {
        if (handleError) {
            const message = error instanceof Error ? error.message : gettext("执行出错");
            alert(message);
        }
        throw error;
    }
}

export async function postJson(url: string, data: any, options: RequestOptions = {}) {
    return request(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
        ...options,
    });
}

export async function get(url: string, options: RequestOptions = {}) {
    return request(url, {
        method: 'GET',
        ...options,
    });
}
